package com.vast.admin.utils;

import com.baomidou.mybatisplus.annotation.TableField;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class TableFieldColumnsUtils<T> {


    private static TableFieldColumnsUtils ourInstance = new TableFieldColumnsUtils();

    public static TableFieldColumnsUtils getInstance() {
        return ourInstance;
    }

    private TableFieldColumnsUtils() {
    }

//    public static Map<String,String> getFieldTableColumns(){
//        Class cla = object.getClass();
//        Map<String,String> columnsItems = new HashMap<>();
//        for (Field field : cla.getDeclaredFields()) {
//            TableField annotation = field.getAnnotation(TableField.class);
//            if (null != annotation) {
//                String fieldName = field.getName();
//                String tableColumnName = annotation.value();
//                System.out.println(fieldName);
//                System.out.println(tableColumnName);
//                columnsItems.put(fieldName,tableColumnName);
//            }
//        }
//        return columnsItems;
//    }

    public Map<String, String> getFieldTableColumns(Class<T> objectClass) {

//        Class cla = object.getClass();
        Map<String,String> columnsItems = new HashMap<>();
        getClassFields(columnsItems, objectClass);

        Class clazz = objectClass.getSuperclass();
        if(clazz != null){
            getClassFields(columnsItems, clazz);
        }

        return columnsItems;
    }

    private void getClassFields(Map<String, String> columnsItems, Class clazz) {
        for (Field field : clazz.getDeclaredFields()) {
            TableField annotation = field.getAnnotation(TableField.class);
            if (null != annotation) {
                String fieldName = field.getName();
                String tableColumnName = annotation.value();
                columnsItems.put(fieldName,tableColumnName);
            }
        }
    }
}
